package crontab

import (
	"fmt"
	cron "github.com/robfig/cron/v3"
	"strconv"
	"time"
	"yak.admin/src/entity"
	"yak.admin/src/util"
)

func init()  {
	crontab := cron.New()
	task := func() {

		db := util.GetMysqlPool().Handler()

		times := util.GetSystemValue("notice_times")
		noticeTimes,_ := strconv.Atoi(times)
		space := util.GetSystemValue("notice_space")
		noticeSpace,_ := strconv.Atoi(space)

		phones := func(province string, city string, county string, t int) ([]*entity.Admin, int) {
			var admins []*entity.Admin
			db.Model(entity.Admin{}).
				Select("nickname, phone").
				Where("send_sms = ?", 1).
				Where("(type = ? and `group` = ?) or (province = ? and city = ? and county = ?)",
					t, entity.AdminSuper, province, city, county).
				Find(&admins)
			return admins, len(admins)
		}

		var drugReport []*entity.DrugReport
		db.Model(entity.DrugReport{}).
			Where("status = ? and notice < ? and reported_at < ?", util.PendingStatus, noticeTimes, time.Now().Unix() - int64(noticeSpace)).
			Find(&drugReport)

		for _,report := range drugReport {
			report.Notice = report.Notice + 1
			//fmt.Println(report.Number)
			// 获取区域及类型超管手机号
			if admins,length := phones(report.Province, report.City, report.County, util.TypeDrug); length > 0 {
				var phones []string
				var signs []string
				var params []map[string]string
				for _,admin := range admins {
					signs = append(signs, "河南省药品评价中心")
					params = append(params, map[string]string{"name": admin.Nickname})
					phones = append(phones, admin.Phone)
				}

				if err := util.SendBatchSms(phones, "SMS_194027367", signs, params); err == nil {
					fmt.Printf("发送成功！")
					db.Save(&report)
				} else {
					fmt.Println(err)
				}
			}
		}


		var deviceReport []*entity.DeviceReport
		db.Model(entity.DeviceReport{}).
			Where("status = ? and notice < ? and reported_at < ?", util.PendingStatus, noticeTimes, time.Now().Unix() - int64(noticeSpace)).
			Find(&deviceReport)

		for _,report := range deviceReport {
			report.Notice = report.Notice + 1
			// fmt.Println(report.Number)
			// 获取区域及类型超管手机号
			if admins, length := phones(report.Province, report.City, report.County, util.TypeDrug); length > 0 {
				var phones []string
				var signs []string
				var params []map[string]string
				for _, admin := range admins {
					signs = append(signs, "河南省药品评价中心")
					params = append(params, map[string]string{"name": admin.Nickname})
					phones = append(phones, admin.Phone)
				}

				if err := util.SendBatchSms(phones, "SMS_194027367", signs, params); err == nil {
					fmt.Printf("发送成功！")
					db.Save(&report)
				} else {
					fmt.Println(err)
				}
			}
		}

	}
	// 添加定时任务, * * * * * 是 crontab,表示每分钟执行一次
	_,_ = crontab.AddFunc("0 */1 * * *", task)
	// 启动定时器
	crontab.Start()
}
